﻿using ConfigSaver;
using Module_Debug.Hardware;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Module_Debug
{
    public partial class ICNA3306_095 : Form
    {
        Configg cfg;
        CaSDK CaSDKObj = new CaSDK();
        CRC16 CRCData = new CRC16();
        private double[,] D_lums;//目标值-单色
        private double[] D_lum = new double[25];//目标值-白色
        private byte[] Send_buf = new byte[1];
        List<string> lines;
        private byte[] Rec_tmp = new byte[1];
        private byte[] Rec_tmp1 = new byte[1];
        private List<byte> buffer = new List<byte>(4096);//默认分配1/16页内存，并始终限制不允许超过  
        private bool Listening = false;//是否没有执行完invoke相关操作   
        private bool IClosing = false;//是否正在关闭串口，执行Application.DoEvents，并阻止再次invoke  
        //创建类型为Person的对象集合
        List<Setting.Gamma_Property> Diven_Gamma = new List<Setting.Gamma_Property>();
        List<Setting.Offset_Property> Diven_Offset = new List<Setting.Offset_Property>();
        byte ICN3306_ID = 0x64;
        string[] DBV_SET = { "", "" };
        string[] GAMMA_SET = { "", "" };
        private List<string> ImageType;

        public static bool firstGammaFlag = true;   //初次打开子窗体标志位
        frmMain frmTop = null;
        public ICNA3306_095(frmMain ICNA3306_095)
        {
            frmTop = ICNA3306_095;
            InitializeComponent();
            frmTop.Child_window_hide_already = true;
            frmTop.Child_Gamma_Window_Open_Enable = false;//防止重复开启子窗体  

            string[] s = { ".bmp" };
            this.ImageType = new List<string>(s);
        }

        #region   //=================================LCD cfg function:OLED_Show_Click====Start=================

        private void OLED_Show_Click(object sender, EventArgs e)
        {
            byte[] TepArr;
            Button btnTmp = (Button)sender;
            //if (!chkBISTMode.Checked)
            {
                Send_buf = new byte[25];

                Setting.TempRecord.cmdLen = 25;

                Send_buf[0] = 0x0A; //LCD配置标志
                Send_buf[2] = 0x15; //数据长度
                switch (btnTmp.Name)
                {
                    case "btnPatternW":                             //写入Pattern参数
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = byte.Parse(numPatternR.Value.ToString());
                            Send_buf[4] = byte.Parse(numPatternG.Value.ToString());
                            Send_buf[5] = byte.Parse(numPatternB.Value.ToString());
                        }
                        break;
                    case "btnred":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0xFF;
                            Send_buf[4] = 0;
                            Send_buf[5] = 0;
                        }
                        break; //R
                    case "btngreen":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0;
                            Send_buf[4] = 0xFF;
                            Send_buf[5] = 0;
                        }
                        break; //G
                    case "btnblue":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0;
                            Send_buf[4] = 0;
                            Send_buf[5] = 0xFF;
                        }
                        break; //B
                    case "btnwhite":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0xFF;
                            Send_buf[4] = 0xFF;
                            Send_buf[5] = 0xFF;
                        }
                        break; //W
                    case "btnblack":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0;
                            Send_buf[4] = 0;
                            Send_buf[5] = 0;
                        }
                        break; //BL
                    default:
                        break;
                }

                CRCData.CalculateCrc16(Send_buf, out Send_buf[23], out Send_buf[24]);
                try
                {
                    frmTop.comPort.Write(Send_buf, 0, 25);
                }
                catch
                {
                    MessageBox.Show("OLED_Show串口有误，请检查", "错误");
                }
            }

            if (chkLvShow.Checked)
            {
                Msr_CA310();
                Thread.Sleep(50);
                auto_lum = frmTop.CASDK_LUM;
                auto_x = frmTop.CASDK_x;
                auto_y = frmTop.CASDK_y;
                txttip.Text = "Lv: " + auto_lum + "\r\n";
            }

        }
        private void numPatternR_ValueChanged(object sender, EventArgs e)
        {
            if (checkBox_Gray.Checked == true)
            {
                numPatternG.Value = numPatternR.Value;
                numPatternB.Value = numPatternG.Value;
            }
        }

        private void checkBox_Gray_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_Gray.Checked)
            {
                numPatternG.Value = numPatternR.Value;
                numPatternB.Value = numPatternR.Value;
                numPatternG.Enabled = false;
                numPatternB.Enabled = false;
            }
            else
            {
                numPatternG.Enabled = true;
                numPatternB.Enabled = true;
            }
        }
        #endregion //=================================LCD cfg function: OLED_Show_Click====end=================     
        #region  //---打开与否的相关处理  以及 串口 返回数据 处理- --- serial Data----
        private void ICNA3306_095_Gamma_FormClosed(object sender, FormClosedEventArgs e)
        {
            ////frmTop.comPort.Close()
            frmTop.comPort.DataReceived -= new SerialDataReceivedEventHandler(ICNA3306_095_DataReceived);
            frmTop.comPort.DataReceived += new SerialDataReceivedEventHandler(frmTop.SerialPort1_DataReceived);
            ////frmTop.comPort.Open();
            frmTop.textBox1.Text = frmTop.textBox1.Text + "ICNA3306_095_Gamma_FormClosed！\r\n";
            frmTop.Child_Gamma_Window_Open_Enable = true; //允许其他子窗体打开
            frmTop.Child_window_hide_already = false;
            frmTop.IC_comboBox.Enabled = true;
            firstGammaFlag = true;
        }
        private void ICNA3306_095_Gamma_VisibleChanged(object sender, EventArgs e)
        {
            if (frmTop.Child_window_hide_already == false) //子窗体已开启标识
            {
                ////frmTop.comPort.Close()
                frmTop.comPort.DataReceived -= new SerialDataReceivedEventHandler(ICNA3306_095_DataReceived);
                frmTop.comPort.DataReceived += new SerialDataReceivedEventHandler(frmTop.SerialPort1_DataReceived);
                ////frmTop.comPort.Open();
                frmTop.textBox1.Text = frmTop.textBox1.Text + "ICNA3306_095_Gamma_FormHide！\r\n";
                frmTop.Child_window_hide_already = true; //子窗体已隐藏标识
            }
            else
            {
                frmTop.comPort.DataReceived -= new SerialDataReceivedEventHandler(frmTop.SerialPort1_DataReceived);
                frmTop.comPort.DataReceived += new SerialDataReceivedEventHandler(ICNA3306_095_DataReceived);
                frmTop.textBox1.Text = frmTop.textBox1.Text + "ICNA3306_095_Gamma_FormOpened！\r\n";
                frmTop.Child_window_hide_already = false; //子窗体已开启标识
            }

        }
        private void ICNA3306_095_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)//Getting data from Comm Port
        {
            if (IClosing)
            { return; }
            try
            {
                Listening = true;//设置标记，说明我已经开始处理数据，一会儿要使用系统UI的。         
                int n = frmTop.comPort.BytesToRead;
                byte[] buf = new byte[n];
                Setting.TempRecord.cmdLen = n;
                frmTop.comPort.Read(buf, 0, n);//读取缓冲数据     
                bool data_1_catched = false;//缓存记录数据是否捕获到    
                buffer.AddRange(buf);
                byte CRCH, CRCL;
                if (buffer.Count > 3)
                {
                    //RECEIVE
                    // 0x0A: 模组Timing参数 设置  返回
                    // 0x0D: 模组的SSD2828配置数据、DriverIC初始化数据  设置  返回
                    // 0x2F: Demura操作    设置  返回
                    // 0x99: 通用读写、寄存器读写  设置  返回
                    // 0x9E: 功耗测试单元  设置  返回
                    if ((buffer[0] == 0x99) && (Setting.TempRecord.cmdLen > 0))
                    {

                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, buffer.Count);  //正确分析一条数据，从缓存中移除数据。  
                            }
                        }
                    }
                    else if ((buffer[0] == 0x6B) && (Setting.TempRecord.cmdLen > 0))
                    {
                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);
                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, buffer.Count);  //正确分析一条数据，从缓存中移除数据。  
                            }
                        }

                    }
                    else if (((buffer[0] == 0x1D) || (buffer[0] == 0x0D) || (buffer[0] == 0x0A) || (buffer[0] == 0x2F) || (buffer[0] == 0x99) || (buffer[0] == 0x9e) || (buffer[0] == 0x9f)) && (Setting.TempRecord.cmdLen > 0))
                    {
                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, buffer.Count);  //正确分析一条数据，从缓存中移除数据。  
                            }
                        }
                    }

                    else
                        buffer.RemoveRange(0, buffer.Count);
                }
                if (data_1_catched)
                {
                    this.Invoke((EventHandler)(delegate
                    {
                        frmTop.T1.Enabled = false; //停止超时计数
                        if (Rec_tmp[0] == 0x6B) //
                        {
                            switch (Rec_tmp[1])
                            {
                                case 0x01:
                                    {
                                        //  if (Rec_tmp[4] == 0x00)
                                        //     frmTop.textBox1.Text = frmTop.textBox1.Text + "DDIC 寄存器\t写 OK！\r\n";
                                        txttip.Text = String.Format("{0:X2}", Rec_tmp[3]) + "寄存器写OK\r\n";
                                    }
                                    break;
                                case 0x02:
                                    {
                                        string tmp = "";                    //8bit  read
                                        //reText.Text = "";
                                        {
                                            for (int i = 0; i <= (Rec_tmp[4] + 1); i++)
                                            {
                                                if (i == (Rec_tmp[4] + 1))
                                                {
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i + 3]);//16进制

                                                }
                                                else if (i == 1)
                                                {
                                                    //不显示回读位数
                                                }
                                                else
                                                {
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i + 3]) + ",";//16进制
                                                }

                                            }
                                        }
                                        // frmTop.Generate_Read_Result_txt.AppendText(tmp + "\r\n");
                                        // reText.Text = tmp;
                                        Application.DoEvents();
                                    }
                                    break;
                                case 0x09:                 //read gamma
                                    {
                                        // if (Rec_tmp[4] == 0x00)
                                        frmTop.textBox1.Text = frmTop.textBox1.Text + "Gamma寄存器Read OK！\r\n";
                                        // frmTop.textBox1.Text = frmTop.textBox1.Text + BitConverter.ToString(Rec_tmp);
                                        int i = 5;
                                        //Array.Copy(Rec_tmp, 5, GammaValueReceived, 0, 150);
                                        for (i = 0; i < 25; i++)
                                        {
                                            GammaValue[i, 0] = (uint)(Rec_tmp[i * 2 + 5] << 8) + Rec_tmp[i * 2 + 6];
                                            GammaValue[i, 1] = (uint)(Rec_tmp[i * 2 + 5 + 50] << 8) + Rec_tmp[i * 2 + 6 + 50];
                                            GammaValue[i, 2] = (uint)(Rec_tmp[i * 2 + 5 + 100] << 8) + Rec_tmp[i * 2 + 6 + 100];
                                        }

                                        for (i = 0; i < 25; i++)
                                        {
                                            DataGirdShow((byte)i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
                                        }
                                    }
                                    break;
                                case 0x0D:
                                    {
                                        //  if (Rec_tmp[4] == 0x00)
                                        //     frmTop.textBox1.Text = frmTop.textBox1.Text + "DDIC 寄存器\t写 OK！\r\n";
                                        txttip.Text = "gamma OTP OK\r\n";
                                    }
                                    break;
                                default: break;

                            }
                        }
                        //--------------------------------------------Power Test---------------
                        else if (Rec_tmp[0] == 0x9E)  // PowerTest
                        {
                            switch (Rec_tmp[3])
                            {
                                case 0x00:
                                    {

                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                        //--------------------------------------------通用读写----------------------------------------------
                        else if (Rec_tmp[0] == 0x99) //GENWR
                        {
                            switch (Rec_tmp[1])
                            {
                                case 0x01:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            txttip.Text = txttip.Text + "DDIC 寄存器\t写 OK！\r\n";
                                    }
                                    break;
                                case 0x02:
                                    {
                                        string tmp = "";                    //8bit  read
                                        {
                                            for (int i = 3; i <= (Rec_tmp[2] + 2); i++)
                                            {
                                                if (i == (Rec_tmp[2] + 2))
                                                {
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]);//16进制
                                                }
                                                else
                                                {
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]) + ",";//16进制
                                                }
                                            }
                                        }
                                        txttip.Text += "DDIC 8bit寄存器--读 OK！\r\n";
                                        txttip.AppendText(tep_tiptxt + tmp + "\r\n");
                                        //Application.DoEvents();
                                        tep_tiptxt = "";
                                    }
                                    break;
                                case 0x03:
                                    {
                                        string tmp = "";
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[3]) + ",";  //16进制
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[4]) + ",";//16进制
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[5]);      //16进制

                                        txttip.Text += "DDIC 16bit寄存器--读 OK！\r\n";
                                        txttip.AppendText(tmp + "\r\n");
                                        Application.DoEvents();
                                    }
                                    break;
                                case 0x04:
                                    {
                                        if (Rec_tmp[3] == 0x00)
                                        {
                                            txttip.Text += "vpp off！\r\n";
                                        }
                                        else if (Rec_tmp[3] == 0x01)
                                        {
                                            txttip.Text += "vpp on！\r\n";
                                        }
                                    }
                                    break;
                            }
                        }
                        //----------------------------------------------------------------------------------------------------                       
                        else if (Rec_tmp[0] == 0x9f)    //小黄窗的通用命令读写
                        {
                            txttip.Text += "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "命令已执行" + "\r\n";
                            txttip.SelectionStart = this.txttip.Text.Length;
                            txttip.ScrollToCaret();//滚动到光标处
                            if (txttip.Lines.Length > 50) txttip.Text = null;
                        }
                    }));
                }
            }
            finally
            {
                Listening = false;
                readokflag = true;
            }
        }

        #endregion //---串口返回数据处理- --- serial Data----
        private void GR_WriteRead_Click(object sender, EventArgs e)          //上位机使用通用命令读写方式操作DDIC
        {
            string str = regSend.Text.ToString();
            byte DDICReg; byte readnum;
            string[] arr;
            arr = str.Split(',');
            Setting.TempRecord.cmdLen = arr.Length + 5;
            Button btnTmp = (Button)sender;

            switch (btnTmp.Name)
            {
                case "writeReg":
                    {
                        String text;
                        text = regSend.Text;
                        frmTop.txtProcessDrivercode(text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
                        {
                            frmTop.SendCmd(0);  //低速
                        }
                        else
                        {
                            frmTop.SendCmd(4); //高速
                        }
                        txttip.Text += "命令已下发...\r\n";
                        txttip.Select(txttip.Text.Length, 0);
                        txttip.ScrollToCaret();
                    }
                    break;
                case "readReg":
                    {
                        DDICReg = byte.Parse(Convert.ToUInt32(arr[0], 16).ToString());
                        try
                        {
                            readnum = byte.Parse(Convert.ToUInt32(arr[1], 16).ToString());
                            frmTop.GeneralRegRead(DDICReg, readnum);
                        }
                        catch
                        {
                            txttip.Text += "读参数异常....\r\n";
                        }

                    }
                    break;

                default:
                    break;
            }
            frmTop.T1.Enabled = false;
            frmTop.T1.Interval = 1000;
            frmTop.T1.Enabled = true;
        }           //上位机使用通用命令读写方式操作DDIC

        private void btnRun_Click(object sender, EventArgs e)   //---复位屏幕，重新点屏
        {
            frmTop.btnRun_Click(frmTop.btnRun, e);
        }
        #region    //---Auto Gamma----------------------
        private void btnSaveGamma_Click(object sender, EventArgs e)
        {
            string tepGammaR = ""; string tepGammaG = ""; string tepGammaB = "";
            string tepstr = "";
            string vtdrGammatxt = "";
            Int16 gdattmp;
            {
                Button btnTmp = (Button)sender;
                switch (btnTmp.Name)
                {
                    case "btnSaveGamma":
                        {
                            //以文本形式保存

                            {//保存
                                SaveFileDialog sf = new SaveFileDialog(); //对话框
                                sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义保存的文件的类型

                                string str = "灰阶序号,灰阶亮度,reg_R,reg_G,reg_B\r\n";
                                if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
                                {
                                    if (sf.FileName == "") return; //如果没有输入文件名
                                    try
                                    {
                                        StreamWriter sw = null; //文件流
                                        sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);
                                        for (int i = 0; i < (this.GammaReg_dataGridView.Rows.Count - 1); i++)
                                        {
                                            str = str + this.GammaReg_dataGridView.Rows[i].Cells[0].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[1].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[2].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[3].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[4].Value.ToString() + "\r\n";
                                        }
                                        sw.WriteLine(str);
                                        sw.Dispose(); //释放资源
                                        sw.Close(); //关闭数据流
                                        MessageBox.Show("数据保存OK！", "系统提示：");

                                    }
                                    catch
                                    {
                                        MessageBox.Show("数据保存时发生错误，请再试！", "系统提示：");
                                    }
                                }

                            }
                        }
                        break;
                    case "btnLoadGamma":
                        {
                            this.GammaReg_dataGridView.Rows.Clear();
                            OpenFileDialog sf = new OpenFileDialog();
                            int Line_Count = 0;
                            string strtmp = "";
                            sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义文件的类型
                            sf.Title = "数据导入";
                            if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
                            {
                                FileStream fs = new FileStream(sf.FileName, FileMode.Open, FileAccess.Read);
                                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                                string strLine = streamReader.ReadLine();
                                while (!string.IsNullOrEmpty(strLine))
                                {
                                    strtmp = strtmp + strLine + ",";
                                    strLine = streamReader.ReadLine(); //循环读取下一行
                                    Line_Count++;
                                }
                                fs.Close(); //关闭流
                                streamReader.Close();
                                string[] arrtmp = strtmp.Split(new Char[] { ',' });
                                for (int j = 1; j <= Line_Count - 1; j++)
                                {
                                    DataGridViewRow Row1 = new DataGridViewRow();
                                    GammaReg_dataGridView.Rows.Add(Row1);
                                }
                                try
                                {
                                    for (int i = 0; i < Line_Count - 1; i++)//有一行标题
                                    {
                                        GammaReg_dataGridView.Rows[i].Cells[0].Value = arrtmp[5 * (i + 1) + 0];
                                        GammaReg_dataGridView.Rows[i].Cells[1].Value = arrtmp[5 * (i + 1) + 1];
                                        GammaReg_dataGridView.Rows[i].Cells[2].Value = arrtmp[5 * (i + 1) + 2];
                                        GammaReg_dataGridView.Rows[i].Cells[3].Value = arrtmp[5 * (i + 1) + 3];
                                        GammaReg_dataGridView.Rows[i].Cells[4].Value = arrtmp[5 * (i + 1) + 4];
                                        //------------------------------------
                                        GammaValue[i, 0] = Convert.ToUInt32(arrtmp[(5 * (i + 1)) + 2]);
                                        GammaValue[i, 1] = Convert.ToUInt32(arrtmp[(5 * (i + 1)) + 3]);
                                        GammaValue[i, 2] = Convert.ToUInt32(arrtmp[(5 * (i + 1)) + 4]);
                                    }
                                    MessageBox.Show("数据导入OK！", "提示：");
                                }
                                catch
                                {
                                    MessageBox.Show("数据导入时发生错误！", "提示：");
                                }
                            }
                        }
                        break;
                    case "btn_CAS200_Clean":
                        {
                            DialogResult dr = MessageBox.Show("确认清空列表数据吗？", "系统提示", MessageBoxButtons.OKCancel);
                            if (dr == DialogResult.OK)
                            {
                                this.GammaReg_dataGridView.Rows.Clear();
                            }
                        }
                        break;

                    default: break;
                }
            }
        }
        private byte Gammnum;
        private double D_x, D_y;
        //private int index = 0;
        private double lum_off, x_off, y_off;
        private double R_x = 0.67;//
        private double R_y = 0.33;
        private double G_x = 0.22;
        private double G_y = 0.71;
        private double B_x = 0.14;
        private double B_y = 0.06;
        private uint[,] GammaValue = new uint[27, 3];//保存当前Gammavalue
        private double auto_lum;  //  存放获取到的产品亮度值
        private double auto_x;
        private double auto_y;        //  存放获取到的产品亮度 色坐标 x,y
        private int index = 1;  //AutoGamma 调整顺序
        private int flag1 = 1;
        private int flag2 = 1;
        private int flag3 = 1;
        bool lastdirupR = true; bool lastdirupG = true; bool lastdirupB = true; // Gamma 调整方向
        private uint step_l = 1;   //Gamma 调节步长
        byte rstep = 16; byte gstep = 16; byte bstep = 16;
        bool STOPAutoGammaFlag = false;     //AutoGamma 停止标志位，解决定时器禁止后AutoGamma无法停止的问题
        byte[] GammaValueTeparr = new byte[54 * 3]; //存放格式化后的GammaValue，以便于直接下发至DDIC
        byte[] ReadBackarr = new byte[32];  //暂存下位机返回数据
        bool GammaReadBackFlag = false; // 下位机返回数据完成标志位
        byte[] GammaValueReceived = new byte[50 * 3]; //存放从下位机接收过来的GammaValue        
        bool ReceivOKFlag = false;
        private int[] ICN3306_Point = new int[27] {//---Gamma绑点数据，这里的数据仅供参考---
            0,1,3,7,11,15,0x13,0x17,0x1b,0x1f,0x23,0x27,0x2f,0x37,0x3f,0x4f,0x5f,0x6f,0x7f,0x8f,0x9f,0xaf,0xbf,0xcf,0xdf,0xef,0xff};
        //byte GPN =  (byte) ICN3306_Point.Length; // 获取Gamma绑点数量
        byte GPN = 0; //保存Gamma绑点数量
        private void btnCalGammaValue_Click(object sender, EventArgs e)   //计算对应绑点灰阶值，并连同暂存的Gammavale显示在窗体表格上
        {
            GPN = (byte)ICN3306_Point.Length; // 获取Gamma绑点数量
            D_lum = new double[GPN];
            {
                this.GammaReg_dataGridView.Rows.Clear();
            }
            for (byte i = 0; i < GPN; i++)
            {
                D_lum[i] = (Math.Pow((ICN3306_Point[i] / 255.0), Convert.ToDouble(txtVT_gamma.Text)) * Convert.ToDouble(txtVT_lum.Text));
                DataGirdShow(i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
            }
        }
        private void GammaValueFormat_Click(object sender, EventArgs e)   //GammaValue 值拆分成 Byte 并与实际地址进行转换 以便于后续处理发送至下位机
        {
            for (int i = 0; i < 15; i++)
            {
                //Gamma R
                GammaValueTeparr[2 * i + 0] = (byte)(GammaValue[i, 0] >> 8);
                GammaValueTeparr[2 * i + 1] = (byte)(GammaValue[i, 0] & 0xff);
            }
            for (int i = 0; i < 15; i++)
            {
                //Gamma G
                GammaValueTeparr[30 + 2 * i + 0] = (byte)(GammaValue[i, 1] >> 8);
                GammaValueTeparr[30 + 2 * i + 1] = (byte)(GammaValue[i, 1] & 0xff);
            }
            for (int i = 0; i < 15; i++)
            {
                //Gamma B
                GammaValueTeparr[60 + 2 * i + 0] = (byte)(GammaValue[i, 2] >> 8);
                GammaValueTeparr[60 + 2 * i + 1] = (byte)(GammaValue[i, 2] & 0xff);
            }
        }

        byte[] Gammaaddr_R = new byte[] { 0, 1, 0x02, 0x03, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 0X2D, 0x2F, 48, 49, 50, 51, 52, 53, 54, 55 };
        byte[] Gammaaddr_G = new byte[] { 0x38, 0x39, 0X3A, 0X3B, 0X3D, 0X3F, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112 };
        byte[] Gammaaddr_B = new byte[] { 113, 114, 115, 116, 117, 118, 119, 120, 12, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 162, 163, 164, 165, 166, 167 };

        private void GammaValueSet(byte rh, byte rl, byte gh, byte gl, byte bh, byte bl, byte index, uint[,] GammaValue)  //把拆分后Gamma值按照DDIC 规定格式排列后送入DDIC
        {   //通过高速方式向第一条Gamma写入一组Gamma值
            string TepArr = ""; //byte[] Gammaaddr_R; byte[] Gammaaddr_G; byte[] Gammaaddr_B;
            string TepArr2 = "";
            string TepArr1 = "";
            string TepArr3 = "";
            try
            {
                TepArr1 = Gammaaddr_R[2 * GPN - 2 * index + 1].ToString("x2") + "," + (GammaValue[GPN - index, 0] & 255).ToString("x2");
                TepArr1 += " " + Gammaaddr_R[2 * GPN - 2 * index + 0].ToString("x2") + "," + (GammaValue[GPN - index, 0] >> 8).ToString("x2");
                frmTop.DDICInitCmdarray = TepArr1.Trim().Split(' ');
                frmTop.SendCmd(4);    //高速写
                TepArr1 = Gammaaddr_G[2 * GPN - 2 * index + 1].ToString("x2") + "," + (GammaValue[GPN - index, 1] & 255).ToString("x2");
                TepArr1 += " " + Gammaaddr_G[2 * GPN - 2 * index + 0].ToString("x2") + "," + (GammaValue[GPN - index, 1] >> 8).ToString("x2");
                frmTop.DDICInitCmdarray = TepArr1.Trim().Split(' ');
                frmTop.SendCmd(4);    //高速写
                TepArr1 = Gammaaddr_B[2 * GPN - 2 * index + 1].ToString("x2") + "," + (GammaValue[GPN - index, 2] & 255).ToString("x2");
                TepArr1 += " " + Gammaaddr_B[2 * GPN - 2 * index + 0].ToString("x2") + "," + (GammaValue[GPN - index, 2] >> 8).ToString("x2");
                frmTop.DDICInitCmdarray = TepArr1.Trim().Split(' ');
                frmTop.SendCmd(4);    //高速写


                //frmTop.SendCmd(4);    //高速写
                Thread.Sleep(20);
                Application.DoEvents();//重点，必须加上，否则父子窗体都假死

            }
            catch
            {
                txttip.Text += "Gamma无法写入，请检查" + "'\r\n";
                txttip.Focus();//获取焦点
                txttip.Select(txttip.TextLength, 0);//光标定位到文本最后
                txttip.ScrollToCaret();//滚动到光标处
                txttip.ForeColor = Color.OrangeRed;
                return;
            }
        }
        private void btnAutoGammas_ICN3306_Click(object sender, EventArgs e)
        {
            int flag = 1;
            numStep.Maximum = 256;
            txttip.ForeColor = Color.Black;
            STOPAutoGammaFlag = false;
            GPN = (byte)ICN3306_Point.Length; // 获取Gamma绑点数量
            double Lr_d, Lg_d, Lb_d;
            D_lums = new double[GPN, 3];
            D_lum = new double[GPN];
            index = 1;  //Gamma绑点序号，第一个绑点通常对应255灰阶
            flag1 = flag2 = flag3 = 1;
            rstep = 16;
            gstep = 16;
            bstep = 16;
            txttip.Text += "GammaValue最大值被限定为: " + GammaValueMax + "\r\n";
            TimTest.Start();
            TimeNow = DateTime.Now; //开始计时

            for (int i = 0; i < GPN; i++)  //计算相应绑点对应的亮度值
            {
                D_lum[i] = (Math.Pow((ICN3306_Point[i] / 255.0), Convert.ToDouble(txtVT_gamma.Text)) * Convert.ToDouble(txtVT_lum.Text));
            }

            D_x = Convert.ToDouble(txtVT_x.Text);  //获取调节目标色坐标 x
            D_y = Convert.ToDouble(txtVT_y.Text); ////获取调节目标色坐标 y
            Lr_d = R_y * ((D_y - G_y) * (B_x - D_x) + (D_x - G_x) * (D_y - B_y)) / B_y / ((D_y - G_y) * (D_x - R_x) + (D_x - G_x) * (R_y - D_y));
            Lb_d = 1.0;
            Lg_d = G_y * ((D_y - R_y) * (B_x - D_x) + (D_x - R_x) * (D_y - B_y)) / B_y / ((D_y - R_y) * (D_x - G_x) + (D_x - R_x) * (G_y - D_y));

            for (int i = 0; i < GPN; i++)   // 通过色坐标已经亮度计算各绑点R/G/B分量对应的亮度值
            {
                D_lums[i, 0] = D_lum[i] * Lr_d / (Lr_d + Lg_d + Lb_d);
                D_lums[i, 1] = D_lum[i] * Lg_d / (Lr_d + Lg_d + Lb_d);
                D_lums[i, 2] = D_lum[i] * Lb_d / (Lr_d + Lg_d + Lb_d);
            }
            labTargetlum.Text = "Tar:" + D_lum[GPN - index].ToString("f4"); ;   //显示当前绑点对应的目标亮度值
            switch (flag)
            {
                case 1://寄存器值与亮度正比
                    {
                        //lum_off = Convert.ToDouble(txtVT_loff.Text);
                        x_off = Convert.ToDouble(txtVT_xoff.Text);   //获取色坐标允差范围
                        y_off = Convert.ToDouble(txtVT_yoff.Text);
                        numPatternR.Value = ICN3306_Point[GPN - index];     //设定绑点灰阶

                        OLED_Show_Click(btnPatternW, e);       //显示255白画面，从255白画面开始调节

                        string TepArr;   //---Unlock ICN3306
                        //TepArr = "FE,20 ;F4,5A     ;    F5,59          ;          fE, 50       ;              A9,50           ;      AA,b0             ;      AB,1";
                        if(rbt_ICNA3306_095_Gamma1.Checked == true) { TepArr = "FE,20 ;F4,5A     ;    F5,59          ;FE,00     ;38    ;FE,50;A9,08;AA,40;AB,01;  FE,00;66,00;        FE, 50       ;            "; }
                        else if(rbt_ICNA3306_095_Gamma2.Checked == true) { TepArr = "FE,20 ;F4,5A     ;    F5,59 ;   FE,00     ;38 ;   FE,60;A9,08;AA,18;AB,01;   FE,00;66,02;      FE, 60       ;            "; }
                        else if(rbt_ICNA3306_095_Gamma3.Checked == true) { TepArr = "FE,20 ;F4,5A     ;    F5,59          ;     FE,30;A9,08;AA,40;AB,01;          FE,00;39;    FE, 30       ;            "; }
                        else { TepArr = "FE,20 ;F4,5A     ;    F5,59          ;  FE,00;66,00;FE,50;A9,08;AA,40;AB,01;         FE, 50       ;            "; }
                        TepArr = TepArr.Replace(" ", ""); //去空格
                        TepArr = TepArr.Replace(";", " "); // “;”换成空格
                        frmTop.DDICInitCmdarray = TepArr.Trim().Split(' ');
                        frmTop.SendCmd(4);    //高速写,//---Unlock ICN3306 End

                        Thread.Sleep(10);
                        Msr_CA310();
                        Msr_CA310(); //修复讨厌的灰阶跳变时CA410数据异常的问题
                        ReceivOKFlag = false;
                        T17.Enabled = true;   //通过T17定时器进行Gamma调整
                    }
                    break;
                case 2:  //寄存器值与亮度反比
                    break;
                default:
                    break;
            }
        }
        private void Msr_CA310()
        {
            frmTop.Msr_CASDK();
            auto_lum = frmTop.CASDK_LUM;
            auto_x = frmTop.CASDK_x;
            auto_y = frmTop.CASDK_y;
        }   //获取CA310/CA410读数

        bool JumpGammaAdjustFlag = false;  //跳过某个绑点标志位，通常用于末尾低灰阶
        UInt32 timeout = 0;
        private void T17_Tick(object sender, EventArgs e)   //AutoGamma处理过程
        {
            double Lr_t, Lg_t, Lb_t, lumr, lumg, lumb;
            T17.Enabled = false;
            T17.Interval = 5;  //不能过短，要给显示画面一个稳定的时间
            //if (!ReceivOKFlag)
            //{
            //    numPatternR.Value = ICN3306_Point[26 - index];
            //    numPatternG.Value = ICN3306_Point[26 - index];
            //    numPatternB.Value = ICN3306_Point[26 - index];
            //    OLED_Show_Click(btnPatternW, e);//写入Pattern参数
            //}
            Msr_CA310();
            txtlvshow.Text = "Lv: " + auto_lum.ToString("f4") + "\r\n" + "x: " + auto_x.ToString("f4") + "\r\n" + "y: " + auto_y.ToString("f4") + "\r\n";
            labTargetlum.Text = "Tar:" + D_lum[GPN - index].ToString("#0.00000");  // 在UI上显示当前绑点的目标亮度值
            txttip.Text += "Adjust inex:" + GPN + "----" + index + "\r\n";

            lum_off = (D_lum[GPN - index] * Convert.ToDouble(numVT_loff.Value) / 1000);  //计算当前绑点允许的亮度误差范围
            x_off = Convert.ToDouble(txtVT_xoff.Text);
            y_off = Convert.ToDouble(txtVT_yoff.Text);       //获取色坐标允许误差范围

            if ((auto_lum < (D_lum[GPN - index] + lum_off)) && (auto_lum > (D_lum[GPN - index] - lum_off)))//
                flag1 = 0;  //判断亮度以及色坐标是否在目标范围
            if ((auto_y < (D_y + y_off)) && (auto_y > (D_y - y_off)) && flag1 == 0)//
                flag2 = 0;  //判断亮度以及色坐标是否在目标范围
            if ((auto_x < (D_x + x_off)) && (auto_x > (D_x - x_off)) && flag1 == 0)//
                flag3 = 0;  //判断亮度以及色坐标是否在目标范围
            if ((flag1 == 0 && flag2 == 0 && flag3 == 0) && (index < 10)) //低灰阶本来就很难调就不这么折腾了
            {   //初次判断调整OK后，再来复测一次，以消除偶发调不准问题
                Msr_CA310();
                if ((auto_lum < (D_lum[GPN - index] + lum_off)) && (auto_lum > (D_lum[GPN - index] - lum_off)))//
                    flag1 = 0;  //判断亮度以及色坐标是否在目标范围
                else flag1 = 1;
                if ((auto_y < (D_y + y_off)) && (auto_y > (D_y - y_off)) && flag1 == 0)//
                    flag2 = 0;  //判断亮度以及色坐标是否在目标范围
                else flag2 = 1;
                if ((auto_x < (D_x + x_off)) && (auto_x > (D_x - x_off)) && flag1 == 0)//
                    flag3 = 0;  //判断亮度以及色坐标是否在目标范围
                else flag3 = 1;
            }//初次判断调整OK后，再来复测一次，以消除偶发调不准问题,

            Lr_t = R_y * ((auto_y - G_y) * (B_x - auto_x) + (auto_x - G_x) * (auto_y - B_y)) / B_y / ((auto_y - G_y) * (auto_x - R_x) + (auto_x - G_x) * (R_y - auto_y));
            Lb_t = 1.0;
            Lg_t = G_y * ((auto_y - R_y) * (B_x - auto_x) + (auto_x - R_x) * (auto_y - B_y)) / B_y / ((auto_y - R_y) * (auto_x - G_x) + (auto_x - R_x) * (G_y - auto_y));
            lumr = auto_lum * Lr_t / (Lr_t + Lg_t + Lb_t);
            lumg = auto_lum * Lg_t / (Lr_t + Lg_t + Lb_t);
            lumb = auto_lum * Lb_t / (Lr_t + Lg_t + Lb_t);

            if (((flag1 == 0 && flag2 == 0 && flag3 == 0) || JumpGammaAdjustFlag) || (timeout > 3 * numTurnGammaTimeout.Value))
            {
                if (timeout > 3 * numTurnGammaTimeout.Value) { txttip.Text = "--模糊处理--\r\n" + "----模糊处理----\r\n" + "--------模糊处理--------\r\n" + "----模糊处理----\r\n" + "--模糊处理--\r\n"; }
                timeout = 0;
                index++;
                if (index == GPN)   //  最后一个绑点通常为0，不用调试结束即可
                {
                    TimTest.Stop();//停止计时
                    txttip.Text = txttip.Text + "ICN3306 gamma调试完毕!\r\n";
                    txttip.Focus();//获取焦点
                    txttip.Select(txttip.TextLength, 0);//光标定位到文本最后
                    txttip.ScrollToCaret();//滚动到光标处
                    STOPAutoGammaFlag = true;
                    btn_ICN3306_Stop.PerformClick();
                    return;
                }
                if (index < GPN)
                {
                    txttip.Text += index + "完成...\r\n";
                    txttip.Select(txttip.Text.Length, 0);
                    txttip.ScrollToCaret();    //上滚提示信息以便于查看
                    for (int i = 0; i < 25; i++)    //本意用于显示当前绑点目标信息，但一般用不到
                    {
                        //Convert.ToString(要转的数, 16);//string s = string.Format("0x{0:X2}", i);    // s = 0x0F;
                        //Points_LV.Text += (i + 1) + ",R/G/B, V" + ICN3306_Point[24 - i] + ": " + string.Format("0x{0:X2}", GammaValue[24 - i, 0]) + "--";
                        //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 1]) + "--";
                        //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 2]) + "\r\n";

                        //this.GammaReg_dataGridView.Rows.Clear();
                        //DataGirdShow((byte)i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
                        //Points_LV.Text += (i + 1) + ",R/G/B, V" + ICN3306_Point[24 - i] + ": " + string.Format("0x{0:X2}", GammaValue[24 - i, 0]) + "--";
                        //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 1]) + "--";
                        //Points_LV.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 2]) + "\r\n";
                    }
                    //Thread.Sleep(10); //1秒=1000毫秒，
                    //T17.Enabled = true;
                    flag1 = 1;  //复位 亮度色坐标符合目标标志位
                    flag2 = 1;
                    flag3 = 1;
                    JumpGammaAdjustFlag = false;
                }
                rstep = (byte)(int.Parse(numStep.Value.ToString())); ;    //重新获取调节步长
                gstep = (byte)(int.Parse(numStep.Value.ToString())); ;
                bstep = (byte)(int.Parse(numStep.Value.ToString())); ;
                numPatternR.Value = ICN3306_Point[GPN - index];     //设定绑点灰阶
                                                                    //numPatternG.Value = ICN3306_Point[GPN - index];
                                                                    //numPatternB.Value = ICN3306_Point[GPN - index];
                                                                    //if (chkTurnsubGamma.Checked)
                                                                    //{
                                                                    //    btnPrevPic_Click(null, null);
                                                                    //}
                                                                    //else
                OLED_Show_Click(btnPatternW, e);//写入Pattern参数   ，显示帮点对应灰阶画面
                //ReceivOKFlag = false;
                Thread.Sleep(10);
                Msr_CA310();
                Msr_CA310(); //修复讨厌的灰阶跳变时CA410数据异常的问题
                if (!STOPAutoGammaFlag)
                    T17.Enabled = true;
            }
            else
            {
                if ((GPN - index == 1) | (GPN - index == 0))//这里index最大值为绑点数量-1；倒数第2个绑点 以及倒数第3个绑点可以做技术处理
                {
                    //GammaValue[0, 1] = 0;  //0绑点不调，直接送零
                    //GammaValue[0, 2] = 0;
                    //GammaValue[0, 0] = 0;
                    GammaValue[GPN - index, 0] = (GammaValue[GPN - index + 1, 0] >> 1) - (GammaValue[GPN - index + 1, 0] >> 2);  //绑点不调，直接赋值算了，如果有过度不均再手动修正即可
                    GammaValue[GPN - index, 1] = (GammaValue[GPN - index + 1, 1] >> 1) - (GammaValue[GPN - index + 1, 1] >> 2);
                    GammaValue[GPN - index, 2] = (GammaValue[GPN - index + 1, 2] >> 1) - (GammaValue[GPN - index + 1, 2] >> 2);
                    JumpGammaAdjustFlag = true;
                }
                //else if (GPN - index == 2) //倒数第2个绑点
                //{
                //}
                else
                {
                    if ((flag3 == 1) | (flag2 == 1) | (flag1 == 1))   //这个判断的意义可以猜猜看
                    {
                        {   //Gamma --R----
                            if (lumr > D_lums[GPN - index, 0])
                            {
                                if ((!lastdirupR)) { timeout++; }
                                if ((!lastdirupR) && (rstep >= 2)) rstep >>= 1;
                                GammaValue[GPN - index, 0] = GammaValue[GPN - index, 0] - rstep;// (byte)(int.Parse(numStep.Value.ToString()));
                                lastdirupR = true;
                            }
                            else
                            {
                                if ((lastdirupR)) { timeout++; }
                                if ((lastdirupR) && (rstep >= 2)) rstep >>= 1;
                                GammaValue[GPN - index, 0] = GammaValue[GPN - index, 0] + rstep;
                                lastdirupR = false;
                            }
                        }
                        {//Gamma ---G--
                            if (lumg > D_lums[GPN - index, 1])
                            {
                                if ((!lastdirupG)) { timeout++; }
                                if ((!lastdirupG) && (gstep >= 2)) gstep >>= 1;
                                GammaValue[GPN - index, 1] = GammaValue[GPN - index, 1] - gstep;
                                lastdirupG = true;
                            }
                            else
                            {
                                if ((lastdirupG)) { timeout++; }
                                if ((lastdirupG) && (gstep >= 2)) gstep >>= 1;
                                GammaValue[GPN - index, 1] = GammaValue[GPN - index, 1] + gstep;
                                lastdirupG = false;
                            }
                        }
                        {//--Gamma  ---B---
                            if (lumb > D_lums[GPN - index, 2])
                            {
                                if ((!lastdirupB)) { timeout++; }
                                if ((!lastdirupB) && (bstep >= 2)) bstep >>= 1;
                                GammaValue[GPN - index, 2] = GammaValue[GPN - index, 2] - bstep;
                                lastdirupB = true;
                            }
                            else
                            {
                                if ((lastdirupB)) { timeout++; }
                                if ((lastdirupB) && (bstep >= 2)) bstep >>= 1;
                                GammaValue[GPN - index, 2] = GammaValue[GPN - index, 2] + bstep;
                                lastdirupB = false;
                            }
                        }
                        txttip.Text += "rstep:" + rstep + "gstetp:" + gstep + "bstep:" + bstep + "\r\n";
                        txttip.Select(txttip.Text.Length, 0);
                        txttip.ScrollToCaret();
                    }   //如果Gamma Value不在目标范围内，此处修正之
                    CheckandCorrectGammaValue();
                    GammaValueFormat_Click(null, null);
                    //显示当前(待)写入的Gamma寄存器值
                    txtGammaValue.Text = GammaValue[GPN - index, 0] + "\r\n" + GammaValue[GPN - index, 1] + "\r\n" + GammaValue[GPN - index, 2] + "\r\n";
                    GammaValueSet(1, 1, 1, 1, 1, 1, (byte)index, GammaValue);
                    Thread.Sleep(20);
                    Application.DoEvents();//重点，必须加上，否则父子窗体都假死                            
                }
                if (!STOPAutoGammaFlag)
                    T17.Enabled = true;
            }
        }
        private void btnVTStop_Click(object sender, EventArgs e)
        {
            T17.Enabled = false;
            Tim_GirAdjust.Enabled = false;
            STOPAutoGammaFlag = true;
            flag1 = 1;
            flag2 = 1;
            flag3 = 1;
            TimTest.Stop();//停止计时
            txttip.ForeColor = Color.Black;
            btnCalculateICN3306.PerformClick();
        }
        private void btnWriteGamma_Click(object sender, EventArgs e)   //检查GammaValue 并且重新转换成指定格式后写入DDIC
        {
            CheckandCorrectGammaValue();   //检查Gamma 是否存在高低灰阶数值错乱 ,并刷新表格数据              
            //GammaValueFormat_Click(null, null);  //Gamma 值与实际地址进行转换 
            string TepArr;   //---Unlock ICN3306
            //TepArr = "FE,20 ;F4,5A     ;    F5,59          ;          fE, 50       ;              A9,50           ;      AA,b0             ;      AB,1";
            if(rbt_ICNA3306_095_Gamma1.Checked == true) { TepArr = "FE,20 ;F4,5A     ;    F5,59          ;          FE, 50       ;            "; }
            else if(rbt_ICNA3306_095_Gamma2.Checked == true) { TepArr = "FE,20 ;F4,5A     ;    F5,59          ;          FE, 60       ;            "; }
            else if(rbt_ICNA3306_095_Gamma3.Checked == true) { TepArr = "FE,20 ;F4,5A     ;    F5,59          ;          FE, 30       ;            "; }
            else { TepArr = "FE,20 ;F4,5A     ;    F5,59          ;          FE, 50       ;            "; }
            TepArr = TepArr.Replace(" ", ""); //去空格
            TepArr = TepArr.Replace(";", " "); // “;”换成空格
            frmTop.DDICInitCmdarray = TepArr.Trim().Split(' ');
            frmTop.SendCmd(4);    //高速写,//---Unlock ICN3306 End
            for (byte i = 1; i <= 27; i++)
            {
                GammaValueSet(0, 0, 0, 0, 0, 0, i, GammaValue); //GammaValue 转换成特定格式后再通过此函数写入DDIC
            }

        }
        uint GammaValueMax = 1024 - 1;
        private void CheckandCorrectGammaValue()   //检查GammaValue 是否按照大小排列
        {
            byte i; GPN = (byte)ICN3306_Point.Length; // 获取Gamma绑点数量
            if (GammaValue[GPN - 1, 0] > GammaValueMax)
            {
                GammaValue[GPN - 1, 0] = GammaValueMax - 16;
            }
            if (GammaValue[GPN - 1, 1] > GammaValueMax)
            {
                GammaValue[GPN - 1, 1] = GammaValueMax - 16;
            }
            if (GammaValue[GPN - 1, 2] > GammaValueMax)
            {
                GammaValue[GPN - 1, 2] = GammaValueMax - 16;
            }  //确保GammaValue不要超过DDIC 中Gamma寄存能接受的最大值


            for (i = (byte)(GPN - 1); i > 0; i--)    //低灰阶GammaValue如果大于高灰阶GammaValue则强制变小
            {
                if (GammaValue[i, 0] < GammaValue[i - 1, 0])
                {
                    GammaValue[i - 1, 0] = GammaValue[i, 0] - 0;
                    //GammaValueFormat_Click(null, null);
                }
                if (GammaValue[i, 1] < GammaValue[i - 1, 1])
                {
                    GammaValue[i - 1, 1] = GammaValue[i, 1] - 0;
                    //GammaValueFormat_Click(null, null);
                }
                if (GammaValue[i, 2] < GammaValue[i - 1, 2])
                {
                    GammaValue[i - 1, 2] = GammaValue[i, 2] - 0;
                    //GammaValueFormat_Click(null, null);
                }
            }
            GammaValue[0, 0] = 0; GammaValue[0, 1] = 0; GammaValue[0, 2] = 0;
            if (chkGammaGridViewFresh.Checked)   // 刷新UI界面GammaValue值显示
            {
                this.GammaReg_dataGridView.Rows.Clear();
                for (i = 0; i < GPN; i++)
                {
                    DataGirdShow(i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
                }
            }
        }
        private void btnGammaValueUpdate_Click(object sender, EventArgs e)      //刷新UI上表格内的Gamma数据
        {
            int Line_Count = 0;
            try
            {
                Line_Count = GammaReg_dataGridView.RowCount;
            }
            catch
            {
                MessageBox.Show("表格数据(行数)异常！", "提示：");
                return;
            }
            try
            {
                for (int i = 0; i < Line_Count - 1; i++)//有一行标题
                {
                    GammaValue[i, 0] = Convert.ToUInt32(GammaReg_dataGridView.Rows[i].Cells[2].Value);
                    GammaValue[i, 1] = Convert.ToUInt32(GammaReg_dataGridView.Rows[i].Cells[3].Value);
                    GammaValue[i, 2] = Convert.ToUInt32(GammaReg_dataGridView.Rows[i].Cells[4].Value);
                }
                //MessageBox.Show("数据更新OK！", "提示：");
                txttip.Text += "Gamma数据更新OK！\r\n";
                btnWriteGamma.PerformClick();
            }
            catch
            {
                MessageBox.Show("Gamma数据更新错误！", "唐韬说：");
            }
        }
        private void numStep_ValueChanged(object sender, EventArgs e)   //手动调整AutoGamma调节步长以在初次调整Gamma是提升速度
        {
            rstep = (byte)(int.Parse(numStep.Value.ToString()));
            gstep = (byte)(int.Parse(numStep.Value.ToString()));
            bstep = (byte)(int.Parse(numStep.Value.ToString()));
        }

        #region  //Gamma调整计时
        System.DateTime TimeNow = new DateTime();
        TimeSpan TimeCount = new TimeSpan();
        private void TimTest_Tick(object sender, EventArgs e)
        {
            TimeCount = DateTime.Now - TimeNow;
            txtTimeShow.Text = string.Format("{0:00}:{1:00}:{2:00}", TimeCount.Hours, TimeCount.Minutes, TimeCount.Seconds);
        }
        #endregion
        private byte[] arrbyte_tmp = new byte[250];         //临时保存下位机返回值
        public void DataGirdShow(byte index, double RRR, double GGG, double BBB)        //UI 表格显示 R/G/B对应Gamma寄存器值
        {
            int Row_Accum = 0, Current_Index = 0, Row_flag = 0;

            DataGridViewRow Row1 = new DataGridViewRow();

            Row_Accum = this.GammaReg_dataGridView.Rows.Count - 1;
            if (Row_Accum != 0)
            {
                Current_Index = this.GammaReg_dataGridView.SelectedCells[0].RowIndex;
                if ((Current_Index != Row_Accum - 1) && (Current_Index != Row_Accum))
                {
                    Row_Accum = Current_Index;
                    Row_flag = 1;
                }
                else
                {
                    this.GammaReg_dataGridView.Rows.Add(Row1);
                }
                if ((Row_Accum != 0) && (Row_flag != 1))
                {
                    if (Current_Index != Row_Accum)
                    {
                        this.GammaReg_dataGridView.Rows[Row_Accum - 1].Selected = false;
                        this.GammaReg_dataGridView.Rows[Row_Accum].Selected = true;
                    }
                }
            }
            else
            {
                this.GammaReg_dataGridView.Rows.Add(Row1);
            }
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[0].Value = index + 1;//序号
            //Rows[x]为第x行,Cells[x]为第x列
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[1].Value = (D_lum[index]).ToString("#0.0000");
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[2].Value = RRR;
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[3].Value = GGG;
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[4].Value = BBB;

            if (Row_flag == 1)
            {
                Row_flag = 0;
                Row_Accum = this.GammaReg_dataGridView.Rows.Count - 1;
                this.GammaReg_dataGridView.Rows[Current_Index].Selected = false;
                this.GammaReg_dataGridView.Rows[Row_Accum - 1].Selected = true;
            }
            GammaReg_dataGridView.FirstDisplayedScrollingRowIndex = GammaReg_dataGridView.RowCount - 1;
        }

        #endregion  //--- Auto Gamma-----
        #region //通用命令处理
        private void Send_Cmd_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            switch (btn.Name)
            {
                case "btnSend1":
                    {
                        frmTop.txtProcessDrivercode(txtCmd1.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend2":
                    {
                        frmTop.txtProcessDrivercode(txtCmd2.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend3":
                    {
                        frmTop.txtProcessDrivercode(txtCmd3.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend4":
                    {
                        frmTop.txtProcessDrivercode(txtCmd4.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend5":
                    {
                        frmTop.txtProcessDrivercode(txtCmd5.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                //case "btnSend6":
                //    {
                //        frmTop.txtProcessDrivercode(txtCmd6.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                //    }
                //    break;
                //case "btnSend7":
                //    {
                //        frmTop.txtProcessDrivercode(txtCmd7.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                //        Msr_CA310(); Msr_CA310();
                //        auto_lum = frmTop.CASDK_LUM;
                //        auto_x = frmTop.CASDK_x;
                //        auto_y = frmTop.CASDK_y;
                //        txttip.Text = "x: " + auto_x + "\r\n";
                //        txttip.Text += "y: " + auto_y + "\r\n";
                //    }
                //    break;
                default: break;
            }
            Setting.TempRecord.cmdLen = 6;
            if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
            {
                frmTop.SendCmd(0);
            }
            else
            {
                frmTop.SendCmd(4);
            }
            txttip.Text += "命令已下发...\r\n";
            txttip.Select(txttip.Text.Length, 0);
            txttip.ScrollToCaret();
        }
        private void SaveCode_Click(object sender, EventArgs e)
        {
            SaveFileDialog txt = new SaveFileDialog();
            txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            string str = "//-----保存Driver IC Code文件------\r\n";
            if (txt.ShowDialog() == DialogResult.OK)
            {
                if (txt.FileName == " ")
                {
                    return;
                }
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(txt.FileName, false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                try
                {
                    if (ChkCMD1.Checked)
                    {
                        str += "//---CMD1---\r\n" + txtCmd1.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    if (ChkCMD2.Checked)
                    {
                        str += "//---CMD2---\r\n" + txtCmd2.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    if (ChkCMD3.Checked)
                    {
                        str += "//---CMD3---\r\n" + txtCmd3.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    if (ChkCMD4.Checked)
                    {
                        str += "//---CMD4---\r\n" + txtCmd4.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    if (ChkCMD5.Checked)
                    {
                        str += "//---CMD5---\r\n" + txtCmd5.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    //if (ChkCMD6.Checked)
                    //{
                    //    str += "//---CMD6---\r\n" + txtCmd5.Text;// lstMIPIDriver.Items[i].ToString();
                    //    str += "\r\n\r\n";
                    //}
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    MessageBox.Show("Driver IC Code保存OK！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("Driver IC Code保存时发生错误，请再试！", "系统提示：");
                }
            }
        }
        private void OpenTxtCode_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;

            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            of.Title = "初始化 Code";

            if (of.ShowDialog() == DialogResult.OK)
            {
                StreamReader streamReader = new StreamReader(of.FileName, Encoding.Default);
                switch (btn.Name)
                {
                    case "OpenTxtCode":
                        {
                            txtCmd1.Clear();
                            txtCmd1.Text = streamReader.ReadToEnd();
                        }
                        break;
                    case "OpenTxtCode2":
                        {
                            txtCmd2.Clear();
                            txtCmd2.Text = streamReader.ReadToEnd();
                        }
                        break;
                    case "OpenTxtCode3":
                        {
                            txtCmd3.Clear();
                            txtCmd3.Text = streamReader.ReadToEnd();
                        }
                        break;
                    case "OpenTxtCode4":
                        {
                            txtCmd4.Clear();
                            txtCmd4.Text = streamReader.ReadToEnd();
                        }
                        break;
                    case "OpenTxtCode5":
                        {
                            txtCmd5.Clear();
                            txtCmd5.Text = streamReader.ReadToEnd();
                        }
                        break;
                    //case "OpenTxtCode6":
                    //    {
                    //        txtCmd6.Clear();
                    //        txtCmd6.Text = streamReader.ReadToEnd();
                    //    }
                    //    break;
                    default: break;
                }
                streamReader.Close();
            }
        }
        #endregion
        string path = "";

        private void Gamma51set(object sender, EventArgs e)
        {
            regSend.Text = "fe,00";
            writeReg.PerformClick();
            Thread.Sleep(20);
            btnAutoGammas_ICN3306.Enabled = true;
        }

        private void ICNA3306_095_Gamma_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }

        #region    //浏览图片
        //string path = "";
        private void btnBrowsePic_Click(object sender, EventArgs e)    //载入画面按键  选择文件夹
        {
            if (txtbmp.Text != "")
            {
                frmTop.defaultfilePath = txtbmp.Text;
            }
            else
            {
                StreamReader streamReader = new StreamReader("./update/Picaddr.txt", Encoding.Default);
                frmTop.defaultfilePath = streamReader.ReadLine();
                streamReader.Close();
            }
            FolderBrowserDialog fldb = new FolderBrowserDialog();
            //首次defaultfilePath为空，按FolderBrowserDialog默认设置（即桌面）选择            
            if (frmTop.defaultfilePath != "")
            {
                //设置此次默认目录为上一次选中目录
                fldb.SelectedPath = frmTop.defaultfilePath;
            }

            fldb.ShowNewFolderButton = false;
            DialogResult res = fldb.ShowDialog();
            if (res != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("没选择任何文件夹.");
                return;
            }
            frmTop.defaultfilePath = fldb.SelectedPath;
            path = fldb.SelectedPath;
            if (!Directory.Exists(path))
            {
                MessageBox.Show("文件夹不存在.");
                return;
            }
            DirectoryInfo di = new DirectoryInfo(path);
            this.listBox3_BMPFile.Items.Clear();
            this.CreateListItem(di);//递归加载文件夹里的所有图片
            txtbmp.Text = path;
            // -------------------------------------------------------------------------
            StreamWriter sw = null; //文件流
            sw = new StreamWriter("./update/Picaddr.txt", false, Encoding.Default);//Encoding.GetEncoding("UTF-8")
            sw.Write(frmTop.defaultfilePath);
            sw.Dispose(); //释放资源
            sw.Close(); //关闭数据流
        }
        /// <summary>
        /// 递归文件夹，把文件夹里所有后缀类似图片的文件，加入listbox
        /// </summary>
        /// <param name="di"></param>
        private void CreateListItem(DirectoryInfo di)
        {
            foreach (DirectoryInfo childDi in di.GetDirectories())
            {
                this.CreateListItem(childDi);
            }

            foreach (FileInfo fi in di.GetFiles())
            {
                if (ImageType.Contains(fi.Extension))//找到一个图片(如果用户手贱把一个excel文件后缀改成jpeg没办法)
                {
                    this.listBox3_BMPFile.Items.Add(new MyImage(fi.FullName));
                }
            }
        }
        private void lstImage_Click(object sender, EventArgs e)
        {
            if (listBox3_BMPFile.SelectedItem == null)
            {
                return;
            }
            MyImage selectedImg = (MyImage)listBox3_BMPFile.SelectedItem;
            Image img = new Bitmap(selectedImg.Path);
            pictureBox1.Image = img;
        }
        private byte ircbmpflag = 1;
        //private void btnPrevPic_Click(object sender, EventArgs e)
        //{
        //    Int32 HACT_True = 0;
        //    Int32 HACT_Skip = 0;
        //    Int32 VACT_True = 0;
        //    Int32 m_txlen = 0;
        //    Int32 j = 0;
        //    FileStream aFile;
        //    string FileName = "";
        //    //byte[] TemFileContent = new byte[1024 * 100];
        //    byte[] TemFileContent = new byte[512 * 4000 + 100];
        //    System.Int32 ByteReaded = 0x00;
        //    //if (chkIRCSendBmp.Checked)
        //    //{
        //    //    if (ircbmpflag == 1)
        //    //        FileName = txtbmp.Text + '\\' + "p16.bmp";
        //    //    else if (ircbmpflag == 2)
        //    //        FileName = txtbmp.Text + '\\' + "p33.bmp";
        //    //    else if (ircbmpflag == 3)
        //    //        FileName = txtbmp.Text + '\\' + "p50.bmp";
        //    //    else if (ircbmpflag == 4)
        //    //        FileName = txtbmp.Text + '\\' + "p75.bmp";
        //    //    else
        //    //    {
        //    //        OLED_Show_Click(btnwhite, e);
        //    //    }
        //    //}
        //    //else
        //    if (chkTurnsubGamma.Checked)
        //    {
        //        FileName = txtbmp.Text + '\\' + "g" + ICN3306_Point[GPN - index] + ".bmp";
        //    }
        //    else if (GirGammaFlag == 255)
        //    {
        //        FileName = txtbmp.Text + '\\' + "sw.bmp";
        //    }
        //    else
        //    {
        //        FileName = txtbmp.Text + '\\' + listBox3_BMPFile.SelectedItem.ToString();
        //    }
        //    try
        //    {
        //        aFile = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        //    }
        //    catch
        //    {
        //        MessageBox.Show("图片地址异常，请检查", "错误");
        //        return;
        //    }

        //    aFile = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        //    ByteReaded = aFile.Read(TemFileContent, 0, 54);
        //    HACT_True = ((TemFileContent[19]) << 8) + TemFileContent[18];
        //    VACT_True = ((TemFileContent[23] << 8) + TemFileContent[22]);

        //    //   if (HACT.Value != HACT_True)
        //    //    {
        //    //          txttip.Text += "图片宽度与设定不符\r\n";
        //    //         return;
        //    //     }
        //    /*
        //    if ((BridgeChipModel.SelectedIndex == 1) && (Dis_mode.SelectedIndex == 1)) //(Dis_mode.SelectedIndex == 1):MIPI 模式，因为下位机仅对MIPI模式做了优化
        //    {
        //        //------------20180903---------------
        //        try
        //        {   //bd 5a a5 9DF0-----提前下个标志位告诉下位机开始送图了，避免特殊图片格式导致错误配置
        //            //BD A5 5A 9DF0-----提前下个标志位告诉下位机开始 快速 送图了
        //            TemFileContent[0] = 0xbd; TemFileContent[1] = 0xa5; TemFileContent[2] = 0x5a; TemFileContent[3] = 0x9d; TemFileContent[4] = 0xf0;
        //            comPort.Write(TemFileContent, 0, 5);
        //        }
        //        catch
        //        {
        //            MessageBox.Show("串口有误，请检查", "错误");
        //            return;
        //        }
        //        //-----------------------------------
        //        try
        //        {

        //            j = 0;
        //            int x, y, s = 0;
        //            x = 512 * 4000; //单次传输数量
        //            y = (VACT_True * HACT_True * 3 / x); //传输次数
        //            if ((VACT_True * HACT_True * 3 % x) != 0)
        //                y++;
        //            {
        //                //aFile.Seek(54, SeekOrigin.Begin);
        //                while (j < y)
        //                {
        //                    //if (HACT_True % 4 != 0)
        //                    //    aFile.Seek((VACT_True - j) * (HACT_True * 3 + (HACT_True % 4)) + 54, SeekOrigin.Begin);
        //                    //else
        //                    //    aFile.Seek((VACT_True - j) * HACT_True * 3 + 54, SeekOrigin.Begin);
        //                    aFile.Seek((j) * x + 54, SeekOrigin.Begin);

        //                    ByteReaded = aFile.Read(TemFileContent, 0, x);

        //                    try
        //                    {
        //                        comPort.Write(TemFileContent, 0, ByteReaded);
        //                    }
        //                    catch
        //                    {
        //                        MessageBox.Show("串口有误，请检查", "错误");
        //                        break;
        //                    }

        //                    progressBar1.Value = Convert.ToInt32((double)m_txlen / aFile.Length * 100);
        //                    label3.Text = progressBar1.Value.ToString() + "%";
        //                    Application.DoEvents();
        //                    j++;
        //                }

        //                TemFileContent[0] = 0x5A;
        //                try
        //                {
        //                    comPort.Write(TemFileContent, 0, 1);
        //                }
        //                catch
        //                {
        //                    MessageBox.Show("串口有误，请检查", "错误");
        //                }

        //                aFile.Close();
        //            }
        //        }
        //        catch
        //        {
        //            MessageBox.Show("请选择文件夹", "错误");
        //        }
        //    }
        //    else*/
        //    {
        //        if ((frmTop.Dis_mode.SelectedIndex == 1) && (Pixel_Offset_Enable.Checked == true)) //video
        //        {
        //            HACT_Skip = HACT_True % 10 > 0 ? (HACT_True + 10 - HACT_True % 10) : HACT_True;
        //        }
        //        else
        //        {
        //            HACT_Skip = HACT_True;
        //        }
        //        try
        //        { //5a a5 9DF0731A-----提前下个标志位告诉下位机开始送图了，避免特殊图片格式导致错误配置
        //            TemFileContent[0] = 0xbd; TemFileContent[1] = 0x5a; TemFileContent[2] = 0xa5; TemFileContent[3] = 0x9d; TemFileContent[4] = 0xf0;
        //            frmTop.comPort.Write(TemFileContent, 0, 5);
        //        }
        //        catch
        //        {
        //            MessageBox.Show("串口有误，请检查", "错误");
        //            return;
        //        }
        //        //-----------------------------------
        //        try
        //        {
        //            //HACT_True = Sig_mode.SelectedIndex > 2 ? Convert.ToInt32(2 * ((TemFileContent[19]<<8)+ TemFileContent[18])) : Convert.ToInt32((TemFileContent[19] << 8) + TemFileContent[18]);
        //            j = 1;
        //            while (j <= VACT_True)
        //            {
        //                //if (Sig_mode.SelectedIndex == 2)
        //                //{
        //                //    aFile.Seek((VACT_True - j) * HACT_True * 2 + 66, SeekOrigin.Begin);
        //                //    ByteReaded = aFile.Read(TemFileContent, 0, HACT_True * 2);
        //                //    try
        //                //    {
        //                //        frmTop.comPort.Write(TemFileContent, 0, HACT_Skip * 2);
        //                //    }
        //                //    catch
        //                //    {
        //                //        MessageBox.Show("串口有误，请检查", "错误");
        //                //        break;
        //                //    }
        //                //    m_txlen += ByteReaded;
        //                //    progressBar1.Value = Convert.ToInt32((double)m_txlen / aFile.Length * 100);
        //                //    label3.Text = progressBar1.Value.ToString() + "%";
        //                //    Application.DoEvents();//重点，必须加上，否则父子窗体都假死
        //                //    j++;
        //                //}
        //                //else
        //                {
        //                    if (HACT_True % 4 != 0)
        //                        aFile.Seek((VACT_True - j) * (HACT_True * 3 + (HACT_True % 4)) + 54, SeekOrigin.Begin);
        //                    else
        //                        aFile.Seek((VACT_True - j) * HACT_True * 3 + 54, SeekOrigin.Begin);

        //                    ByteReaded = aFile.Read(TemFileContent, 0, HACT_True * 3); // 
        //                    try
        //                    {
        //                        frmTop.comPort.Write(TemFileContent, 0, HACT_Skip * 3);
        //                    }
        //                    catch
        //                    {
        //                        MessageBox.Show("串口有误，请检查", "错误");
        //                        break;
        //                    }
        //                    m_txlen += ByteReaded;
        //                    progressBar1.Value = Convert.ToInt32((double)m_txlen / aFile.Length * 100);
        //                    label3.Text = progressBar1.Value.ToString() + "%";
        //                    Application.DoEvents();//重点，必须加上，否则父子窗体都假死
        //                    j++;
        //                }
        //            }

        //            TemFileContent[0] = 0x5A;
        //            try
        //            {
        //                frmTop.comPort.Write(TemFileContent, 0, 1);
        //            }
        //            catch
        //            {
        //                MessageBox.Show("串口有误，请检查", "错误");
        //                return;
        //            }
        //            aFile.Close();
        //        }
        //        catch
        //        {
        //            txttip.Text += "啥图片都没显示";
        //            txttip.Select(txttip.Text.Length, 0);
        //            txttip.ScrollToCaret();
        //        }
        //    }
        //}
        public class MyImage
        {
            public MyImage(string p)
            {
                this.Path = p;
            }
            public string Path { get; set; }
            public override string ToString()
            {
                if (Path == null)
                {
                    return null;
                }
                return System.IO.Path.GetFileName(this.Path);
            }
        }
        //-----------------------------------------
        #endregion

        private void btnCleanTextBox_Click(object sender, EventArgs e)
        {
            txttip.Enabled = true;
            txttip.Clear();
        }

        private void btnReadGamma_Click(object sender, EventArgs e)
        {
            txttip.Text += "先设定对应的Page" + "\r\n";
            uint tep;
            btnCalculateICN3306.PerformClick();
            for (byte i = 0; i < 27; i++)
            {
                //Gammaaddr_R
                frmTop.GeneralRegRead(Gammaaddr_R[2 * i + 1], 1);
                readokflag = false;  //重置接收数据完成标志位
                while (!readokflag) { Application.DoEvents(); }   //等待接收完成标志；Application.DoEvents()：避免进程卡死
                //txttip.Text += Rec_tmp[4] + "\r\n";
                //Application.DoEvents(); Thread.Sleep(200); Application.DoEvents();
                tep = Rec_tmp[4];
                frmTop.GeneralRegRead(Gammaaddr_R[2 * i + 0], 1);
                //Application.DoEvents(); Thread.Sleep(200); Application.DoEvents();
                readokflag = false;  //重置接收数据完成标志位
                while (!readokflag) { Application.DoEvents(); }   //等待接收完成标志；Application.DoEvents()：避免进程卡死
                //txttip.Text += Rec_tmp[4] + "\r\n";
                tep += (uint)(Rec_tmp[4] << 8);
                GammaValue[i, 0] = tep;

                //Gammaaddr_G
                frmTop.GeneralRegRead(Gammaaddr_G[2 * i + 1], 1);
                readokflag = false;  //重置接收数据完成标志位
                while (!readokflag) { Application.DoEvents(); }   //等待接收完成标志；Application.DoEvents()：避免进程卡死

                tep = Rec_tmp[4];
                frmTop.GeneralRegRead(Gammaaddr_G[2 * i + 0], 1);
                readokflag = false;  //重置接收数据完成标志位
                while (!readokflag) { Application.DoEvents(); }   //等待接收完成标志；Application.DoEvents()：避免进程卡死                
                tep += (uint)(Rec_tmp[4] << 8);
                GammaValue[i, 1] = tep;

                //Gammaaddr_B
                frmTop.GeneralRegRead(Gammaaddr_B[2 * i + 1], 1);
                readokflag = false;  //重置接收数据完成标志位
                while (!readokflag) { Application.DoEvents(); }   //等待接收完成标志；Application.DoEvents()：避免进程卡死

                tep = Rec_tmp[4];
                frmTop.GeneralRegRead(Gammaaddr_B[2 * i + 0], 1);
                readokflag = false;  //重置接收数据完成标志位
                while (!readokflag) { Application.DoEvents(); }   //等待接收完成标志；Application.DoEvents()：避免进程卡死                
                tep += (uint)(Rec_tmp[4] << 8);
                GammaValue[i, 2] = tep;
            }

            this.GammaReg_dataGridView.Rows.Clear();
            for (byte i = 0; i < GPN; i++)
            {
                DataGirdShow(i, GammaValue[i, 0], GammaValue[i, 1], GammaValue[i, 2]);
            }

        }

        string defaultfilePath = "";

        private void ICNA3306_095_Load(object sender, EventArgs e)
        {
            GPN = (byte)ICN3306_Point.Length; // 获取Gamma绑点数量
            cfg = new Configg(@"c:\Users\Public\694\UserConfig", this, true);
            cfg.Add("命令窗口1", txtCmd1, "//命令窗口1");
            cfg.Add("命令窗口2", txtCmd2, "//命令窗口2");
            cfg.Add("命令窗口3", txtCmd3, "//命令窗口3");
            cfg.Add("命令窗口4", txtCmd4, "//命令窗口4");
            cfg.Add("命令窗口5", txtCmd5, "//命令窗口5");
            cfg.Add("FE,00", regSend, "FE,00");
            //cfg.Add("465", DbvMaxlum, "465");//DbvMaxlum
            cfg.LoadConfig();
            ////--下面几行代码为读取xml中现有Key
            //NameValueCollection sAll;
            //sAll = ConfigurationManager.AppSettings;
            //foreach (string s in sAll.AllKeys)
            //    txttip.Text += ("Key: " + s + " Value: " + sAll.Get(s)) + "\r\n";

        }

        private string tep_tiptxt = "";  //保存返回值提示信息
        bool readokflag = false;

    }
}
